package com.monk.provider;

import com.netflix.hystrix.exception.HystrixTimeoutException;
import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 官网示例：https://docs.spring.io/spring-cloud-netflix/docs/2.2.6.RELEASE/reference/html/#hystrix-fallbacks-for-routes
 * 自定义的服务降级方法
 * @author Monk
 */
@Component
public class CustomFallBack implements FallbackProvider {
    @Override
    public String getRoute() {
        /**
         * 指定使用当前服务降级的路由服务名称（区分大小写，需要和对应微服务工程下application.yml中的spring。application.name一致）
         * * 表示所有微服务均使用当前服务降级方法
         */
        return "server-power";
    }

    @Override
    public ClientHttpResponse fallbackResponse(String route, Throwable cause) {
        if (cause instanceof HystrixTimeoutException) {
            return response(HttpStatus.GATEWAY_TIMEOUT);
        } else {
            return response(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    private ClientHttpResponse response(final HttpStatus status) {
        return new ClientHttpResponse() {
            @Override
            public HttpStatus getStatusCode() throws IOException {
                return status;
            }

            @Override
            public int getRawStatusCode() throws IOException {
                return status.value();
            }

            @Override
            public String getStatusText() throws IOException {
                return status.getReasonPhrase();
            }

            @Override
            public void close() {
            }

            @Override
            public InputStream getBody() throws IOException {
                StringBuffer buffer = new StringBuffer();
                buffer.append("{code: ").append(getRawStatusCode()).append(", ");
                buffer.append("msg: ").append(getStatusText()).append("}");
                return new ByteArrayInputStream(buffer.toString().getBytes());
            }

            @Override
            public HttpHeaders getHeaders() {
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_JSON);
                return headers;
            }
        };
    }
}
